package cn.yunyichina.provider.message.thread.app;

import cn.yunyichina.provider.framework.data.SpringContextHandler;
import cn.yunyichina.provider.framework.dubbo.service.AlipayService;
import cn.yunyichina.provider.framework.dubbo.service.WechatPayService;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.provider.iface.entity.message.AppMessageVo;
import cn.yunyichina.provider.iface.entity.pay.PaymentSettingResponse;
import cn.yunyichina.provider.message.dao.TextTemplateDao;
import cn.yunyichina.provider.message.entity.OrgAppTemplate;
import cn.yunyichina.provider.message.entity.TextTemplate;
import cn.yunyichina.provider.message.utils.MsgAppUtils;
import cn.yunyichina.utils.commons.StringUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import cn.yunyichina.utils.log.Log;
import cn.yunyichina.utils.log.constant.LogParamType;
import cn.yunyichina.utils.log.constant.LogScene;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 文本推送
 * Created by Joe.zhou on 2017/12/13.
 */
public class MsgTextAppPushRunnable implements Runnable{
    private static Logger logger = LoggerFactory.getLogger(MsgTextAppPushRunnable.class);

    private final String METHOD_NAME = "MsgTextAppPushRunnable";

    private AppMessageVo appMessageVo;

    private ResponseObject responseObject;

    private TextTemplateDao textTemplateDao = SpringContextHandler.getBean(TextTemplateDao.class);

    public MsgTextAppPushRunnable(AppMessageVo appMessageVo, ResponseObject responseObject) {
        this.appMessageVo = appMessageVo;
        this.responseObject = responseObject;
    }

    @Override
    public void run() {
        Log.i(LogScene.MSG_TXT,METHOD_NAME, LogParamType.REQUEST,appMessageVo.getOpenId(), JsonUtils.toJsonString(appMessageVo));
        try {
            if(appMessageVo != null){
                OrgAppTemplate orgAppTemplat = MsgAppUtils.getOrgAppTemplat(JsonUtils.toJsonString(appMessageVo));
                //获取推送文本表信息
                TextTemplate textTemplate = new TextTemplate();
                textTemplate.setTemplateCode(orgAppTemplat.getLibraryTemplateCode());
                textTemplate.setPlatformType(orgAppTemplat.getPlatformType());
                List<TextTemplate> tmpTemplates = textTemplateDao.select(textTemplate);
                if(tmpTemplates.size() < 1){
                    Log.i(LogScene.MSG_TXT,METHOD_NAME, LogParamType.NORMAL,appMessageVo.getOpenId(),"获取ImageTemplate失败：" + JsonUtils.toJsonString(textTemplate));
                    responseObject.setResultCodeAndMessage("8201" , "获取ImageTemplate失败：" + JsonUtils.toJsonString(textTemplate));
                    return;
                }
                textTemplate = tmpTemplates.get(0);
                logger.info("MsgTextAppPushRunnable 获取到文本消息实体：" + JsonUtils.toJsonString(textTemplate));

                //获取支付配置
                PaymentSettingResponse paymentSettingResponse = MsgAppUtils.getPaymentSettingResponse(appMessageVo.getPlatformOrgAppCode() ,
                        StringUtils.isBlank(appMessageVo.getDevOrgCode())? "" : appMessageVo.getDevOrgCode() , orgAppTemplat.getPlatformType().intValue());
                if(paymentSettingResponse == null){
                    Log.i(LogScene.MSG_TXT,METHOD_NAME, LogParamType.NORMAL,appMessageVo.getOpenId(),"获取PaymentSettingResponse支付配置失败：" + JsonUtils.toJsonString(appMessageVo));
                    responseObject.setResultCodeAndMessage("8201" , "MsgTextAppPushRunnable 获取PaymentSettingResponse支付配置失败：" + JsonUtils.toJsonString(appMessageVo));
                    return;
                }

                JSONObject param = new JSONObject();
                Response response = null;

                String contentStr = MsgAppUtils.getResultTextMsgContentStr(textTemplate, appMessageVo);
                logger.info("MsgTextAppPushRunnable 获取ContentStr：" + contentStr);

                param.put("payment_setting" , paymentSettingResponse);
                param.put("to_user" , appMessageVo.getOpenId());
                param.put("org_app_code" , appMessageVo.getPlatformOrgAppCode());
                param.put("org_code" , appMessageVo.getDevOrgCode());
                param.put("template_id" , orgAppTemplat.getPayTemplateId());
                param.put("msg_content" , contentStr);
                param.put("platform_type" , appMessageVo.getPlatformType());

                //根据推送平台不同分发
                if(orgAppTemplat.getPlatformType() == 1){  //微信
                    Log.i(LogScene.MSG_TXT,METHOD_NAME, LogParamType.NORMAL,appMessageVo.getOpenId(),"调用Wechat文本消息发送："+ JsonUtils.toJsonString(param));
                    response = WechatPayService.callHumpFromInternal("yyt.wechatpay.wechat.message.text.send", JsonUtils.toJsonString(param));
                    Log.i(LogScene.MSG_TXT,METHOD_NAME, LogParamType.NORMAL,appMessageVo.getOpenId(),"调用Wechat文本消息发送返回："+ JsonUtils.toJsonString(response));
                    responseObject.setResultCodeAndMessage(response.getResultCode() , "MsgTextAppPushRunnable 调用Wechat模板消息返回：" + response.getResultMessage());
                }else if(orgAppTemplat.getPlatformType() == 2) { //支付宝
                    Log.i(LogScene.MSG_TXT,METHOD_NAME, LogParamType.NORMAL,appMessageVo.getOpenId(),"调用Alipay文本消息发送："+ JsonUtils.toJsonString(param));
                    response = AlipayService.callHumpFromInternal("yyt.alipay.alipaymessage.text.send", JsonUtils.toJsonString(param));
                    Log.i(LogScene.MSG_TXT,METHOD_NAME, LogParamType.NORMAL,appMessageVo.getOpenId(),"调用Alipay文本消息发送返回："+ JsonUtils.toJsonString(response));
                    responseObject.setResultCodeAndMessage(response.getResultCode() , "MsgTextAppPushRunnable 调用Alipay模板消息返回：" + response.getResultMessage());
                }else{
                    Log.i(LogScene.MSG_TXT,METHOD_NAME, LogParamType.NORMAL,appMessageVo.getOpenId(),"获取OrgAppTemplate 发送平台错误，请检查数据库配置：" + orgAppTemplat.getPlatformType());
                    responseObject.setResultCodeAndMessage("8201" , "MsgTextAppPushRunnable 获取OrgAppTemplate 发送平台错误，请检查数据库配置：" + orgAppTemplat.getPlatformType());
                    return;
                }
            }
        } catch (Exception e) {
            Log.e(LogScene.MSG_TXT , "MsgTextAppPushRunnable 执行方法异常！" , e);
            responseObject.setResultCodeAndMessage(Response.FAILURE_CODE , "MsgTextAppPushRunnable 执行方法异常！");
        }
    }
}
